//
//  WJWeatherViewController.m
//  天气
//
//  Created by dllo on 16/8/22.
//  Copyright © 2016年 WJ. All rights reserved.
//
// 天气的城市代码表 http://blog.csdn.net/huoer_12/article/details/17357281
// 城市天气接口 http://tqapi.mobile.360.cn/city/101101110
//  http://tqapi.mobile.360.cn/city/101310204

#import "WJWeatherViewController.h"
#import "NSString+WJDateString.h"
#import "WJNavinationView.h"
#import "WJHeaderView.h"
#import "AFNetworking.h"
#import "WJCityModel.h"
#import <CoreLocation/CoreLocation.h>
#import "WJNetTool.h"
#import "WJCityViewController.h"
#import "WJWeatherTableViewCell.h"
#import "WJIndexTwoTableViewCell.h"
#import "WJIndexThreeTableViewCell.h"
#import "BezierCurveView.h"

#define kWJWidth  [UIScreen mainScreen].bounds.size.width
#define kWJHeight [UIScreen mainScreen].bounds.size.height

@interface WJWeatherViewController ()<CLLocationManagerDelegate,UITableViewDataSource,UITableViewDelegate>
// TableView
@property (nonatomic, strong) UITableView *tableView;
// 头视图
@property (nonatomic, strong) WJHeaderView *header;
// 定位
@property (nonatomic, strong) CLLocationManager *manager;
// 得到的地点
@property (nonatomic, copy) NSString *placeStr;
// 所有城市编码
@property (nonatomic, copy) NSMutableArray *cityCode;
// 网址
@property (nonatomic, copy) NSString *urlStr;
// 传过来的城市
@property (nonatomic, copy) NSString *passCity;

@property (nonatomic, assign) BOOL isOK;

@property (nonatomic, strong) WJCityModel *model;
// 夜间的数组
@property (nonatomic,retain) NSMutableArray *nightArray;
// 白天的数组
@property (nonatomic,retain) NSMutableArray *dayArray;

@property (nonatomic, strong) BezierCurveView *dayView;

@property (nonatomic, strong) BezierCurveView *nightView;

@end

@implementation WJWeatherViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.placeStr.length == 0) {
        // 3.开始定位
        [self.manager startUpdatingLocation];
    }
    
    self.dayArray = [NSMutableArray array];
    
    self.nightArray = [NSMutableArray array];
    
    self.isOK = YES;
    
    // 本地的城市编码
    [self analysisCityData];
    
    // 导航栏
    [self createConfig];
    
    // 创建TableView
    [self createView];
}

- (void)analysisCityData
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"weatherPlist" ofType:@"txt"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSArray *array = dic[@"zone"];
    
    // 根据编码
    // 数组套字典 cityArray {"市名": "北京", "编码": "101010100"}
    NSMutableArray *cityArray = [NSMutableArray array];
    for (NSDictionary *dic in array) {
        
        NSArray *array = dic[@"zone"];
        for (NSDictionary *dic in array) {
            [cityArray addObject:dic[@"zone"]];
        }
        
    }
    
    // 数组套字典 cityArray1  {"北京": "101010100"}
    NSMutableArray *array1 = [NSMutableArray array];
    for (NSArray *array in cityArray) {
        for (NSDictionary *dic in array) {
            
            NSString *cityName = dic[@"name"];
            NSString *code = dic[@"code"];
            NSDictionary *cityDic =[ NSDictionary  dictionaryWithObjectsAndKeys:code,cityName, nil];
            [array1 addObject:cityDic];
            
        }
    }
    self.cityCode = array1;
}

#pragma mark  - 输入一个字符得到 城市天气编码
- (NSString *)codeOfCityName:(NSString *)cityName
{
    for (NSDictionary *dic in self.cityCode) {
        if ([dic.allKeys.lastObject isEqualToString:cityName]) {
            return [dic valueForKey:cityName];
        }
    }
    return nil;
}


- (void)createConfig
{
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    image.image = [UIImage imageNamed:@"bg2.jpg"];
    image.userInteractionEnabled = YES;
    [self.view addSubview:image];
    
    WJNavinationView *view = [[WJNavinationView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64)];
    view.lable.text = @"今日天气";
    view.Block = ^(){
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
    [self.view addSubview:view];
}


- (void)createView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kWJWidth, kWJHeight - 24) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor clearColor];
    
    self.header = [[WJHeaderView alloc]initWithFrame:CGRectMake(0, 64, kWJHeight, 350)];
    [self.header.placeButton addTarget:self action:@selector(exchangeCity) forControlEvents:1<<6];
    self.tableView.tableHeaderView = self.header;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[WJWeatherTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[WJIndexTwoTableViewCell class] forCellReuseIdentifier:@"two"];
    [self.tableView registerClass:[WJIndexThreeTableViewCell class] forCellReuseIdentifier:@"three"];
}

// 点击进入下一页
- (void)exchangeCity
{
    WJCityViewController *cityVC = [[WJCityViewController alloc]init];
    cityVC.Block = ^(NSDictionary *cityDic){
        
        if (![self.placeStr isEqualToString:cityDic.allKeys[0]]) {
            
            self.urlStr = [NSString stringWithFormat:@"http://tqapi.mobile.360.cn/city/%@",cityDic.allValues[0]];
            NSString *str = [NSString stringWithFormat:@"%@ [点击切换]",cityDic.allKeys[0]];
            [self.header.placeButton setTitle:str forState:0];
            [self createData];
            
        }
        
    };
    [self.navigationController pushViewController:cityVC animated:YES];
}


#pragma mark - UITableView dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        WJWeatherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.hourly_forecast = self.model.hourly_forecast;
        [cell.collectionView reloadData];
        return cell;
        
    }else if (indexPath.row == 1){
        
        WJIndexTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"two"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.dayArray = self.dayArray;
        cell.nightArray = self.nightArray;
        
        cell.firstCollection.weather = self.model.weather;
        [cell.firstCollection.collectionView reloadData];
        
        cell.sectionCollectionView.weather = self.model.weather;
        [cell.sectionCollectionView.collectionView reloadData];
        
        cell.thirdCollectionView.weather = self.model.weather;
        [cell.thirdCollectionView.collectionView reloadData];
        
        return cell;
        
    }else {
        
        WJIndexThreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"three"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.life = self.model.life;
        [cell.collectionView reloadData];
        return cell;
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        return 170;
        
    }else if (indexPath.row == 1){
        
        return 500;
        
    }else {
        
        return 330;
        
    }
}


//  数组里面存放着定位的所有位置
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    if (self.isOK) {
        
        CLLocation *location = [locations firstObject];
        [self.manager stopUpdatingLocation];
        
        self.isOK = NO;
        
        /** 根据经纬度来进行反地理编码 */
        dispatch_async(dispatch_get_main_queue(), ^{
            
            CLGeocoder *geocoder = [[CLGeocoder alloc]init];
            [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
                
                // 如果有错误 或者 解析出来的地址为0
                if (placemarks.count == 0 || error) return;
                
                CLPlacemark *pm = [placemarks firstObject];
                self.placeStr = pm.locality;
                
                NSString *str = [NSString stringWithFormat:@"%@ [点击切换]",self.placeStr];
                [self.header.placeButton setTitle:str forState:0];
                
                NSString *str4 = [self.placeStr stringByReplacingOccurrencesOfString:@"市" withString:@""];
                NSString *cityCode= [self codeOfCityName:str4];
                
                self.urlStr = [NSString stringWithFormat:@"http://tqapi.mobile.360.cn/city/%@",cityCode];
                                
                // 创建数据
                [self createData];
                
            }];
            
        });
        
    }
}


- (void)createData
{
    [SVProgressHUD show];
    
    [WJNetTool GET:self.urlStr body:nil header:nil response:WJDATA success:^(id resuposeObject) {
        
        
        NSString * str = [[NSString alloc] initWithData:resuposeObject encoding:NSUTF8StringEncoding];
        
        if (str.length > 100) {
            
            NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
            
            if(err) {
                NSLog(@"json解析失败：%@",err);
            }
            
            self.model = [[WJCityModel alloc]initWithDic:dic];
            
            self.header.realtime = self.model.realtime;
            
            self.header.pm25 = self.model.pm25;
            
            
            [self.dayArray removeAllObjects];
            [self.nightArray removeAllObjects];
            
            for (NSDictionary *dic in self.model.weather){
                
                NSArray *dayArray = dic[@"info"][@"day"];
                NSArray *nightArray = dic[@"info"][@"night"];
                [self.dayArray addObject:dayArray[2]];
                [self.nightArray addObject:nightArray[2]];
            }
            [SVProgressHUD dismiss];
            
            [self.tableView reloadData];
            
            
        }else{
            
            [WJNetTool GET:str body:nil header:nil response:WJJSON success:^(id resuposeObject) {
                
                self.model = [[WJCityModel alloc]initWithDic:resuposeObject];
                
                self.header.realtime = self.model.realtime;
                
                self.header.pm25 = self.model.pm25;
                
                [self.dayArray removeAllObjects];
                [self.nightArray removeAllObjects];
                
                for (NSDictionary *dic in self.model.weather) {
                    
                    NSArray *dayArray = dic[@"info"][@"day"];
                    NSArray *nightArray = dic[@"info"][@"night"];
                    [self.dayArray addObject:dayArray[2]];
                    [self.nightArray addObject:nightArray[2]];
                }
                [SVProgressHUD dismiss];
                [self.tableView reloadData];
                
            } failure:^(NSError *error) {
                
                [SVProgressHUD showErrorWithStatus:@"链接失败"];
            }];
        }
        
    } failure:^(NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:@"链接失败"];
        
    }];
}

#pragma MARK - 懒加载
- (CLLocationManager *)manager
{
    if (_manager == nil) {
        
        _manager = [[CLLocationManager alloc]init];
        _manager.delegate = self;
        
        // 3. 位置间隔之后重新定位
        _manager.distanceFilter = 10;
        
        // 4. 定位的精确度
        _manager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        
        // 必须设置的
        [_manager requestAlwaysAuthorization];//始终授权
        [_manager requestWhenInUseAuthorization];// 使用时授权
    }
    return _manager;
}


@end
